<template>
  <div class="consumption-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>消费记录管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchQuery"
            placeholder="请输入用户姓名或消费项目"
            clearable
            @clear="handleSearchClear"
            @keyup.enter.native="handleSearch"
          >
            <template slot="append">
              <el-button @click="handleSearch">
                <i class="el-icon-search"></i>
              </el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="16" class="text-right">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i>新增记录
          </el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
            <i class="el-icon-delete"></i>批量删除
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-area">
      <el-table
        :data="filteredRecords"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="userName" label="用户姓名" width="120" sortable />
        <el-table-column prop="consumptionItem" label="消费项目" width="150" />
        <el-table-column prop="amount" label="金额(元)" width="120" sortable>
          <template slot-scope="scope">
            {{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="consumptionTime" label="消费时间" width="180" sortable />
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template slot-scope="scope">
            <el-tag :type="getPaymentMethodTagType(scope.row.paymentMethod)">
              {{ scope.row.paymentMethod }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="small" @click="handleEdit(scope.row)" type="primary" plain>
              <i class="el-icon-edit"></i>编辑
            </el-button>
            <el-button size="small" @click="handleDelete(scope.row)" type="danger" plain>
              <i class="el-icon-delete"></i>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-area">
      <el-pagination
        :current-page.sync="currentPage"
        :page-size.sync="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :small="true"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredRecords.length"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="isEditMode ? '编辑消费记录' : '新增消费记录'"
      width="50%"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="消费项目" prop="consumptionItem">
          <el-input v-model="formData.consumptionItem" placeholder="请输入消费项目" />
        </el-form-item>
        <el-form-item label="金额(元)" prop="amount">
          <el-input-number
            v-model="formData.amount"
            :min="0"
            :precision="2"
            :step="0.1"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="消费时间" prop="consumptionTime">
          <el-date-picker
            v-model="formData.consumptionTime"
            type="datetime"
            placeholder="选择消费时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="formData.paymentMethod" placeholder="请选择支付方式">
            <el-option label="现金" value="现金" />
            <el-option label="微信支付" value="微信支付" />
            <el-option label="支付宝" value="支付宝" />
            <el-option label="银行卡" value="银行卡" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      dialogVisible: false,
      isEditMode: false,
      formRef: null,
      formData: {
        id: null,
        userName: '',
        consumptionItem: '',
        amount: 0,
        consumptionTime: '',
        paymentMethod: '',
        remarks: ''
      },
      formRules: {
        userName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
        ],
        consumptionItem: [
          { required: true, message: '请输入消费项目', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          { type: 'number', min: 0, message: '金额必须大于0', trigger: 'blur' }
        ],
        consumptionTime: [
          { required: true, message: '请选择消费时间', trigger: 'change' }
        ],
        paymentMethod: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ]
      },
      records: [
        {
          id: 1,
          userName: '张三',
          consumptionItem: '餐饮消费',
          amount: 128.5,
          consumptionTime: '2025-06-10 12:30:45',
          paymentMethod: '微信支付',
          remarks: '午餐消费'
        },
        {
          id: 2,
          userName: '李四',
          consumptionItem: '购物消费',
          amount: 599.0,
          consumptionTime: '2025-06-12 15:20:30',
          paymentMethod: '支付宝',
          remarks: '购买衣服'
        },
        {
          id: 3,
          userName: '王五',
          consumptionItem: '娱乐消费',
          amount: 88.0,
          consumptionTime: '2025-06-15 20:10:15',
          paymentMethod: '现金',
          remarks: '电影票'
        },
        {
          id: 4,
          userName: '赵六',
          consumptionItem: '交通消费',
          amount: 25.5,
          consumptionTime: '2025-06-18 08:45:00',
          paymentMethod: '微信支付',
          remarks: '打车费用'
        },
        {
          id: 5,
          userName: '钱七',
          consumptionItem: '医疗消费',
          amount: 320.0,
          consumptionTime: '2025-06-20 10:30:00',
          paymentMethod: '银行卡',
          remarks: '药品购买'
        }
      ]
    }
  },
  computed: {
    filteredRecords() {
      let result = this.records
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(
          item =>
            item.userName.toLowerCase().includes(query) ||
            item.consumptionItem.toLowerCase().includes(query)
        )
      }
      return result
    }
  },
  methods: {
    getPaymentMethodTagType(method) {
      switch (method) {
        case '微信支付':
          return 'success'
        case '支付宝':
          return 'primary'
        case '银行卡':
          return 'warning'
        case '现金':
          return ''
        default:
          return 'info'
      }
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    handleSearch() {
      this.currentPage = 1
    },
    handleSearchClear() {
      this.currentPage = 1
    },
    handleAdd() {
      this.isEditMode = false
      this.resetForm()
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.isEditMode = true
      this.formData = Object.assign({}, row)
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确定要删除这条消费记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.records = this.records.filter(item => item.id !== row.id)
          this.$message.success('删除成功')
        })
        .catch(() => {})
    },
    handleBatchDelete() {
      if (this.selectedRows.length === 0) return
      this.$confirm(`确定要删除选中的${this.selectedRows.length}条记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const idsToDelete = this.selectedRows.map(item => item.id)
          this.records = this.records.filter(item => !idsToDelete.includes(item.id))
          this.selectedRows = []
          this.$message.success('删除成功')
        })
        .catch(() => {})
    },
    resetForm() {
      this.formData = {
        id: null,
        userName: '',
        consumptionItem: '',
        amount: 0,
        consumptionTime: '',
        paymentMethod: '',
        remarks: ''
      }
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
    },
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        if (this.isEditMode) {
          // 编辑模式
          const index = this.records.findIndex(item => item.id === this.formData.id)
          if (index !== -1) {
            this.records.splice(index, 1, Object.assign({}, this.formData))
          }
          this.$message.success('修改成功')
        } else {
          // 新增模式
          const newId = this.records.length > 0 ? Math.max(...this.records.map(item => item.id)) + 1 : 1
          this.records.push(Object.assign({}, this.formData, { id: newId }))
          this.$message.success('新增成功')
        }
        this.dialogVisible = false
      })
    }
  },
  mounted() {
    this.loading = true
    setTimeout(() => {
      // 模拟异步加载
      // 数据已在 data 里初始化
      this.loading = false
    }, 500)
  }
}
</script>

<style scoped>
.consumption-container {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: center;
}

.el-table {
  margin-top: 10px;
}

.el-tag {
  margin-right: 5px;
}
</style>